package com.zimu.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.blade.mvc.annotation.*;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.multipart.FileItem;
import com.zimu.example.model.Person;
import com.zimu.example.service.CutImage;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import java.util.Optional;

/**
 * @author : zimu
 * @Date: 2018/7/19 15:33
 * @description :
 */
@Path("req")
public class RequestController {
    @GetRoute("name")
    public void getName(Request request){
//        String name = request.query("username", "jack");
//        System.out.println(name);
        Optional<String> nameOptional = request.query("username");
        nameOptional.ifPresent(name -> System.out.println(name));
    }

    @GetRoute("/users/:id")
    public void getId(Request request){
        Integer id = request.pathInt("id");
        System.out.println("id="+id);
    }

    @PostRoute("save")
    @JSON
    public String savePerson(@Param Person person, Request request){
        System.out.println(person);
        request.attribute("person", person);
        return "show.html";
    }

    @PostRoute("/upload")
    public void upload(Request request, @Param String avatar_data, Response response){
        Optional<FileItem> fileItem = request.fileItem("avatar_file");
        JSONObject jsonObject = JSONObject.parseObject(avatar_data);

        fileItem.ifPresent(item -> {
            System.out.println(item);
            byte[] data = item.getData();
            try {
                FileOutputStream fileOutputStream = new FileOutputStream("1.jpg");
                fileOutputStream.write(data);
                fileOutputStream.close();
                CutImage cutImage = new CutImage();
                cutImage.cutImage("1.jpg", "2.jpg",jsonObject.getInteger("x"),
                        Math.abs(jsonObject.getInteger("y")),jsonObject.getInteger("width"),
                        jsonObject.getInteger("height"));
                File file = new File("1.jpg");
                file.delete();
//                cutImage("a.jpg", "c:",(Integer) jsonObject.get("x"),
//                        (Integer)jsonObject.get("y"),(Integer)jsonObject.get("width"), (Integer)jsonObject.get("height"));
            }catch (Exception e){
                e.printStackTrace();
            }
        });
    }
}
